<!--
 * @Author: Wangtao
 * @Date: 2020-09-28 10:50:52
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-06-15 19:09:04
-->
<template>
  <div
    :class="{ callSummary: true }"
    style="height: 100%"
    v-loading="componentLoading"
    element-loading-text="正在加载数据..."
  >
    <div
      :class="{
        'call-right-box': true,
        isCallCard: ['CallCard', 'AutoCallTask'].includes(
          localCallData.importType
        ),
        isDataCenterCall: ['DataCenterCall', 'webchatDataCenter'].includes(
          localCallData.importType
        ),
        empty: isEmpty,
        shadow: shadow
      }"
    >
      <!-- #region 客户卡片小蓝条 -->
      <!-- {{ localCallData.custId === '' ? '空' : localCallData.custId }}
      {{ localCallData.custName === '' ? '空' : localCallData.custName }}
      {{ currentCustom.name === '' ? '空' : currentCustom.name }}
      {{ customerList.length }} -->
      <div
        class="call-customer-card clearfix"
        :style="{
          height: ['webchatTodo'].includes(localCallData.importType)
            ? '100px'
            : '68px'
        }"
      >
        <div class="item-right fl">
          <!-- 第一行 客户信息相关 -->
          <div class="first-line clearfix" style="width: 100%">
            <!-- [ 全新客户 ] 永远展示未知客户 -->
            <span
              v-if="
                customerList.length === 0 &&
                [
                  'DataCenterCall',
                  'CallCard',
                  'AutoCallTask',
                  'AutoCallTaskScreen'
                ].includes(localCallData.importType)
              "
              style="color: #303854; font-weight: bold"
            >
              未知客户
            </span>
            <!-- [ 通话弹屏 ] 展示下拉框，可增可修改 -->
            <span
              v-else-if="
                ['CallCard', 'AutoCallTaskScreen'].includes(
                  localCallData.importType
                )
              "
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <el-dropdown
                trigger="click"
                placement="bottom-end"
                @command="handleCommand"
              >
                <span class="el-dropdown-link customer-name">
                  <span v-if="currentCustom.id">{{
                    currentCustom.name || ' '
                  }}</span>
                  <span v-else>创建客户</span>
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="(item, index) in customerList"
                    :key="index"
                    :command="item"
                  >
                    {{ item.name }}
                  </el-dropdown-item>
                  <el-dropdown-item command="new" divided>
                    <el-button type="text" icon="el-icon-plus"
                      >创建客户</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <div
                v-if="
                  $store.state.common.session.account.mpShifted &&
                  currentCustom.id
                "
                style="display: flex; justify-content: space-between"
              >
                <DistributeBtn
                  :customerId="currentCustom.id"
                  :wechatShow="true"
                  @updateLog="updatePersonOrAddrOrLog(activeName)"
                />
                <el-dropdown>
                  <i
                    class="V7_iconfont V7_iconV7tubiao_shusandian"
                    style="
                      color: #767e91;
                      margin-left: 4px;
                      font-size: 20px;
                      cursor: pointer;
                    "
                  ></i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>
                      <Phone :showBtn="false" :data="newCusDetailData" />
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-functions="['customer_workorder_insert']"
                    >
                      <el-dropdown @command="handleWork">
                        <span><i class="el-icon-plus"></i>工单</span>
                        <el-dropdown-menu slot="dropdown">
                          <template v-if="busCategory && busCategory.length">
                            <el-dropdown-item
                              :command="item.id"
                              v-for="item in busCategory"
                              :key="item.id"
                              >{{ item.modelName }}</el-dropdown-item
                            >
                          </template>
                          <template v-else>
                            <el-dropdown-item command="none"
                              >暂无工单</el-dropdown-item
                            >
                          </template>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </el-dropdown-item>
                    <el-dropdown-item v-functions="['customer_contact_insert']">
                      <Person
                        :showBtn="false"
                        :customerId="currentCustom.id"
                        @updatePerson="updatePersonOrAddrOrLog(activeName)"
                      ></Person>
                    </el-dropdown-item>
                    <el-dropdown-item v-functions="['customer_address_insert']">
                      <Address
                        :showBtn="false"
                        :customerId="currentCustom.id"
                        @updateAddr="updatePersonOrAddrOrLog(activeName)"
                      ></Address>
                    </el-dropdown-item>
                    <el-dropdown-item v-functions="['customer_follow_insert']">
                      <TrackButton
                        :showBtn="false"
                        :customerId="currentCustom.id"
                      ></TrackButton>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </span>
            <!-- [ 数据中心 - 通话记录 ] 展示纯文本，可增不可修改 -->
            <span
              v-else-if="
                ['DataCenterCall', 'AutoCallTask'].includes(
                  localCallData.importType
                )
              "
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <span v-if="localCallData.custId === ''">
                <el-dropdown
                  trigger="click"
                  placement="bottom-end"
                  @command="handleCommand"
                >
                  <span class="el-dropdown-link customer-name">
                    {{ currentCustom.name }}
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="(item, index) in customerList"
                      :key="index"
                      :command="item"
                    >
                      {{ item.name }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
              <span v-else>
                {{ currentCustom.name || '' }}
              </span>
              <div
                v-if="
                  $store.state.common.session.account.mpShifted &&
                  currentCustom.id
                "
                style="display: flex; justify-content: space-between; align-items center"
              >
                <DistributeBtn
                  :customerId="currentCustom.id"
                  :wechatShow="true"
                  @updateLog="updatePersonOrAddrOrLog(activeName)"
                />
                <el-dropdown>
                  <i
                    class="V7_iconfont V7_iconV7tubiao_shusandian"
                    style="
                      color: #767e91;
                      margin-left: 4px;
                      font-size: 20px;
                      cursor: pointer;
                    "
                  ></i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>
                      <Phone :showBtn="false" :data="newCusDetailData" />
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-functions="['customer_workorder_insert']"
                    >
                      <el-dropdown @command="handleWork">
                        <span><i class="el-icon-plus"></i>工单</span>
                        <el-dropdown-menu slot="dropdown">
                          <template v-if="busCategory && busCategory.length">
                            <el-dropdown-item
                              :command="item.id"
                              v-for="item in busCategory"
                              :key="item.id"
                              >{{ item.modelName }}</el-dropdown-item
                            >
                          </template>
                          <template v-else>
                            <el-dropdown-item command="none"
                              >暂无工单</el-dropdown-item
                            >
                          </template>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </el-dropdown-item>
                    <el-dropdown-item v-functions="['customer_contact_insert']">
                      <Person
                        :showBtn="false"
                        :customerId="currentCustom.id"
                        @updatePerson="updatePersonOrAddrOrLog(activeName)"
                      ></Person>
                    </el-dropdown-item>
                    <el-dropdown-item v-functions="['customer_address_insert']">
                      <Address
                        :showBtn="false"
                        :customerId="currentCustom.id"
                        @updateAddr="updatePersonOrAddrOrLog(activeName)"
                      ></Address>
                    </el-dropdown-item>
                    <el-dropdown-item v-functions="['customer_follow_insert']">
                      <TrackButton
                        :showBtn="false"
                        :customerId="currentCustom.id"
                      ></TrackButton>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </span>
            <span
              v-else-if="
                ['webchatTodo', 'webchatDataCenter'].includes(
                  localCallData.importType
                )
              "
            >
              <template v-if="$store.state.common.session.account.mpShifted">
                <div
                  v-if="currentCustom.id"
                  style="display: flex; justify-content: space-between"
                >
                  <el-tooltip
                    effect="dark"
                    :content="currentCustom.name"
                    placement="top"
                  >
                    <span class="current-name">{{ currentCustom.name }}</span>
                  </el-tooltip>
                  <span
                    class="fr positioning"
                    style="width: 100px; margin-left: 16px; text-align: right"
                  >
                    <el-tooltip
                      effect="dark"
                      content="取消关联"
                      placement="top"
                    >
                      <i
                        v-functions="['customer_relate']"
                        class="V7_iconfont V7_iconV7tubiao_quxiaoguanlian"
                        style="color: #767e91"
                        @click="cancelRelationCus"
                      >
                      </i>
                    </el-tooltip>
                    <el-tooltip
                      effect="dark"
                      content="关联客户"
                      placement="top"
                    >
                      <i
                        v-functions="['customer_relate']"
                        class="V7_iconfont V7_iconV7tubiao_guanlian"
                        style="color: #767e91; margin-left: 14px"
                        @click="relatedCustomers('update')"
                      >
                      </i>
                    </el-tooltip>
                    <DistributeBtn
                      :customerId="currentCustom.id"
                      :wechatShow="true"
                      @updateLog="updatePersonOrAddrOrLog(activeName)"
                    />
                    <el-dropdown>
                      <i
                        class="V7_iconfont V7_iconV7tubiao_shusandian"
                        style="
                          color: #767e91;
                          margin-left: 4px;
                          font-size: 20px;
                          position: relative;
                          top: 3px;
                        "
                      ></i>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item>
                          <Phone :showBtn="false" :data="newCusDetailData" />
                        </el-dropdown-item>
                        <el-dropdown-item
                          v-functions="['customer_workorder_insert']"
                        >
                          <el-dropdown @command="handleWork">
                            <span><i class="el-icon-plus"></i>工单</span>
                            <el-dropdown-menu slot="dropdown">
                              <template
                                v-if="busCategory && busCategory.length"
                              >
                                <el-dropdown-item
                                  :command="item.id"
                                  v-for="item in busCategory"
                                  :key="item.id"
                                  >{{ item.modelName }}</el-dropdown-item
                                >
                              </template>
                              <template v-else>
                                <el-dropdown-item command="none"
                                  >暂无工单</el-dropdown-item
                                >
                              </template>
                            </el-dropdown-menu>
                          </el-dropdown>
                        </el-dropdown-item>
                        <el-dropdown-item
                          v-functions="['customer_contact_insert']"
                        >
                          <Person
                            :showBtn="false"
                            :customerId="currentCustom.id"
                            @updatePerson="updatePersonOrAddrOrLog(activeName)"
                          ></Person>
                        </el-dropdown-item>
                        <el-dropdown-item
                          v-functions="['customer_address_insert']"
                        >
                          <Address
                            :showBtn="false"
                            :customerId="currentCustom.id"
                            @updateAddr="updatePersonOrAddrOrLog(activeName)"
                          ></Address>
                        </el-dropdown-item>
                        <el-dropdown-item
                          v-functions="['customer_follow_insert']"
                        >
                          <TrackButton
                            :showBtn="false"
                            :customerId="currentCustom.id"
                          ></TrackButton>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </span>
                </div>
                <div v-else>
                  <span style="color: #303854; font-weight: bold"
                    >未知客户</span
                  >
                  <span
                    class="fr positioning"
                    v-functions="['customer_relate']"
                  >
                    <i
                      class="V7_iconfont V7_iconV7tubiao_guanlian"
                      style="cursor: pointer; color: #767e91"
                      @click.stop="relatedCustomers('create')"
                    ></i>
                  </span>
                </div>
              </template>
              <template v-else>
                <div v-if="currentCustom.name">
                  {{ currentCustom.name }}
                  <span class="fr positioning" @click="LocaCustomer('update')">
                    <span class="V7_iconfont V7_iconV7tubiao_gengxin"></span>
                    更新客户
                  </span>
                </div>
                <div v-else>
                  <span style="color: #303854; font-weight: bold"
                    >未知客户</span
                  >
                  <span class="fr positioning" @click="LocaCustomer('add')">
                    <span class="V7_iconfont V7_iconV7tubiao_guanlian"></span>
                    关联客户
                  </span>
                </div>
              </template>
            </span>
          </div>
          <!-- 在线工作台信息相关 -->
          <div
            v-if="
              ['webchatTodo', 'webchatDataCenter'].includes(
                localCallData.importType
              )
            "
            class="second-line clearfix"
          >
            <span
              class="customer-info peer"
              :title="currentWebchatData.queueName || '--'"
              slot="reference"
              >技能组：{{ currentWebchatData.queueName || '--' }}</span
            >
            <span class="customer-info"
              >接入号：{{ currentWebchatData.accessName || '--' }}</span
            >
            <el-popover placement="top-start" width="250" trigger="hover">
              <webchatProcessInfo
                :processInfo="webchatProcessData"
              ></webchatProcessInfo>
              <span
                class="customer-info processInfo"
                slot="reference"
                :style="{
                  display:
                    localCallData.importType === 'webchatTodo'
                      ? 'block'
                      : 'inline',
                  margin:
                    localCallData.importType === 'webchatTodo' ? '5px 0px' : ''
                }"
              >
                会话流程：<span class="processInfoName">{{
                  currentWebchatData.processName || '--'
                }}</span>
              </span>
            </el-popover>
            <span
              class="customer-info"
              v-show="localCallData.importType === 'webchatDataCenter'"
              >接待座席：{{ currentWebchatData.userName }}</span
            >
            <el-tooltip
              effect="dark"
              :content="getQtText()"
              placement="bottom"
              slot="reference"
            >
              <div v-if="getQtestingStatus === 'scored'" slot="content">
                {{ '质检分数:' + propData.webchatDetails.gradeScore }}分<br />
                {{ '质检点评:' + propData.webchatDetails.comments }}
              </div>
              <span
                v-functions="['webchat_session_chat_commit_cancel_qc']"
                v-show="
                  ['webchatDataCenter'].includes(localCallData.importType)
                "
                @click="handleQualitytesting"
                style="cursor: pointer; color: #767e91"
                :class="['fr', 'V7_iconfont', getQtIcon()]"
              ></span>
            </el-tooltip>
          </div>
          <!-- 自动外呼弹屏 -->
          <div
            class="second-line clearfix"
            v-else-if="
              ['AutoCallTaskScreen'].includes(localCallData.importType)
            "
          >
            <span class="customer-info"
              >任务名称：{{ currentCallData.taskName || '--' }}</span
            >
          </div>
          <!-- 自动外呼详情里的通话记录 -->
          <div
            class="second-line clearfix"
            v-else-if="
              ['AutoCallTask'].includes(localCallData.importType) ||
              currentCallData.callType === 'autoDialout'
            "
          >
            <span class="customer-info"
              >任务名称：{{ currentCallData.taskName || '--' }}</span
            >
            <span class="customer-info">
              <span>外显号码：{{ currentCallData.displayNumber || '-' }}</span>
              <span
                style="margin-left: 4px"
                v-if="currentCallData.callerProvince"
                >({{ currentCallData.callerProvince }}-{{
                  currentCallData.callerCity
                }})</span
              >
            </span>
            <span class="customer-info"
              >语音导航：{{ currentCallData.ivrName || '-' }}</span
            >
            <span
              class="customer-info peer"
              :title="currentCallData.queueName || '--'"
              >技能组：{{ currentCallData.queueName || '-' }}</span
            >
          </div>
          <!-- 第二行 通话信息相关 -->
          <div class="second-line clearfix" v-else>
            <span
              v-show="
                ['dialout', 'transfer', 'consultTransfer'].indexOf(
                  currentCallData.callType
                ) > -1
              "
            >
              <span class="customer-info"
                >外显号码：{{ currentCallData.displayNumber || '-' }}</span
              >
              <span
                class="customer-info"
                style="margin-left: 4px"
                v-if="currentCallData.callerProvince"
                >({{ currentCallData.callerProvince }}-{{
                  currentCallData.callerCity
                }})</span
              >
            </span>
            <span
              v-show="
                ['incoming', 'transfer', 'consultTransfer'].indexOf(
                  currentCallData.callType
                ) > -1
              "
            >
              <span class="customer-info"
                >服务号：{{ currentCallData.trunkNumber || '-' }}</span
              >
              <span class="customer-info"
                >语音导航：{{ currentCallData.ivrName || '-' }}</span
              >
              <span
                class="customer-info peer"
                :title="currentCallData.queueName || '--'"
                >技能组：{{ currentCallData.queueName || '-' }}</span
              >
            </span>
          </div>
        </div>
      </div>
      <div
        class="webchatAddLabel fl"
        v-if="
          ['webchatTodo', 'webchatDataCenter'].includes(
            localCallData.importType
          )
        "
        v-functions="['webchat_session_chat_tag']"
      >
        <addLabel
          ref="webchatAddLabelRef"
          :customerLabelShow="false"
          @afoldFun="afoldFun"
          @addLabelSave="webchatAddLabel"
          :labelArr="webchatLabelArr"
          :labelTreeData="webchatLabelTree"
          :labelTreeObj="webchatLabelTreeObj"
        >
        </addLabel>
      </div>
      <!-- #endregion -->
      <customTab
        :tabs="tabsList"
        :value="activeName"
        :isShowTabConfig="true"
        @input="setFunTabName"
        @newTabClick="newTabClick"
        @checkHeadersChange="checkHeadersChange"
      ></customTab>
      <keep-alive>
        <component
          :is="moduleLoaded"
          :ref="activeName"
          :key="activeName"
          @handle-oprate="handleOprate"
          @afterAddCustRecord="afterAddCustRecord"
          @afterEditCustRecord="afterEditCustRecord"
          @getNewCusDetail="getNewCusDetail"
          @updateChatCard="updateChatCard"
          :commonData="childData"
          :moduleType="moduleType"
          :showListen="showListen"
          :showDowload="showDowload"
          :newCusDetailData="newCusDetailData"
          :id="currentCustom.id"
          :inputType="inputType"
          :busCategory="busCategory"
          :style="{
            height: 'calc(100vh - ' + (componentHeight + labelHeight) + 'px)'
          }"
        ></component>
      </keep-alive>
      <dockPage
        :style="{
          height: 'calc(100vh - ' + (componentHeight + labelHeight) + 'px)'
        }"
        v-show="moduleLoaded === ''"
        :dockUrlList="dockUrlList"
        :currentDockPageUrl="childData.currentDockPageUrl"
      >
      </dockPage>
    </div>
    <updateCustomer
      :drawer="drawer"
      @closeDraw="closeDraw"
      @afterAddCustRecord="afterAddCustRecord"
    ></updateCustomer>
    <el-dialog
      class="new-customer"
      title="关联客户"
      :modal="false"
      :visible.sync="showAllNewCuntomer"
    >
      <div style="display: flex">
        <el-select style="flex: 1" v-model="form.name" placeholder="请选择">
          <el-option
            v-for="item in newCuntomerOptions"
            :key="item.prop"
            :label="item.label"
            :value="item.prop"
          >
          </el-option>
        </el-select>
        <el-input
          style="flex: 2; margin-left: 10px"
          v-model="form.value"
          prefix-icon="el-icon-search"
          placeholder="请输入搜索内容"
          clearable
          @input="handleSearchNewCus"
        ></el-input>
      </div>
      <configTable
        :data="showTableData"
        :showPagination="false"
        :selection="false"
      >
        <template slot="radio">
          <u-table-column width="30">
            <template slot-scope="{ row }">
              <el-radio
                v-model="relationCus"
                :label="row._id"
                @change="chooseCustomer(row)"
              >
              </el-radio>
            </template>
          </u-table-column>
        </template>
        <template slot="column">
          <template v-for="(item, index) in newCuntomerOptions">
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :show-overflow-tooltip="true"
              v-if="item.prop === 'name'"
            >
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :show-overflow-tooltip="true"
              v-if="item.prop === 'mobile'"
            >
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :show-overflow-tooltip="true"
              v-if="item.prop === 'wechat'"
            >
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :show-overflow-tooltip="true"
              v-if="item.prop === 'email'"
            >
            </u-table-column>
          </template>
        </template>
      </configTable>
      <div class="btns">
        <el-button @click="cancelNewCusListPop">取消</el-button>
        <el-button type="primary" @click="saveRelationCus">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :destroy-on-close="true"
      :visible.sync="workShow"
      :modal="false"
      :show-close="false"
      class="work"
    >
      <EditBusiness
        ref="addOrEditBusinessRef"
        :title="title"
        :agentList="agentListArr"
        @cancelFun="back"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import customTab from '@/components/commonSummary/customTab.vue'
import { commonAction, formatStamp, encrypt, deepClone, checkHideTel } from '@/utils/common'
import { Component, Vue, Prop, Watch, Ref } from 'vue-property-decorator'
import webchatProcessInfo from '@/views/webchat/common/webchatProcessInfo.vue'
import updateCustomer from '@/components/updateCustomer/index.vue'
import addLabel from '@/components/addLabel/index.vue'
import dockPage from '@/components/commonSummary/detailTab/dockPage.vue'
import { CommonModule } from '@/store/modules/common'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import DistributeBtn from '@/views/newCustomer/components/buttons/distribute.vue'
import TrackButton from '@/views/newCustomer/components/buttons/track.vue'
import Address from '@/views/newCustomer/components/buttons/address.vue'
import Person from '@/views/newCustomer/components/buttons/person.vue'
import Phone from '@/views/newCustomer/components/buttons/phone.vue'
import EditBusiness from '@/afterSales/views/business/components/editBusiness.vue'
import { WebchatModule } from '@/store/modules/webchat'
export function handTagTree (options: any, arg: any) {
  for (let i = 0; i < options?.length; i++) {
    const ele = options[i]
    if (!ele.isEnabled) {
      // 过滤停用
      continue
    }
    const obj: any = {
      name: ele.name,
      _id: ele._id,
      children: []
    }
    arg.Arr.push(obj)
    ele.children = ele.children || []
    ele.children.length > 0 ? handTagTree(ele.children, { Arr: obj.children }) : delete obj.children
    if (obj.children && obj.children.length === 0) {
      delete obj.children
    }
  }
}
@Component({
  name: 'CallSummay',
  components: {
    EditBusiness,
    DistributeBtn,
    TrackButton,
    Address,
    Person,
    Phone,
    configTable,
    customTab,
    webchatProcessInfo,
    updateCustomer,
    addLabel,
    dockPage,
    tabCustomer: () => import('@/components/commonSummary/detailTab/customer.vue'),
    tabTicket: () => import('@/components/commonSummary/detailTab/ticket.vue'),
    tabContact: () => import('@/components/commonSummary/detailTab/History.vue'),
    tabCalldetail: () => import('@/components/commonSummary/detailTab/callDetail.vue'),
    // dockPage: () => import('@/components/commonSummary/detailTab/dockPage.vue'),
    tabWebchatInfo: () => import('@/views/webchat/common/webchatInfo.vue'),
    tabCustomerNew: () => import('@/components/commonSummary/detailTab/newCustomer.vue'),
    tabQuickReply: () => import('@/views/webchat/common/quickReply.vue'),
    tabWebchatSessionDetails: () => import('@/views/dataCenter/webchatData/webchatSessionDetails.vue'),
    tabPerson: () => import('@/components/commonSummary/detailTab/person.vue'),
    tabAddress: () => import('@/components/commonSummary/detailTab/address.vue'),
    tabRecord: () => import('@/components/commonSummary/detailTab/record.vue')
  }
})
export default class CallSummay extends Vue {
  [x: string]: any
  @Ref() private readonly webchatAddLabelRef !: addLabel
  @Ref() private readonly addOrEditBusinessRef
  @Prop({
    default: () => {
      return {}
    }
  }) private propData!: any

  @Prop() private isShowDrawer!: any
  @Prop() private randomNum: number | undefined
  @Prop({ default: 330 }) private componentHeight!: string
  @Prop({ default: false }) private shadow!: boolean
  @Prop({ default: '' }) private moduleType!: string // 每个模块的微前端ID
  @Prop({ default: false }) private showDowload!: boolean
  @Prop({ default: false }) private showListen!: boolean
  @Prop() private visitorId
  @Prop() private inputType
  private componentLoading: boolean = false
  private labelHeight: number = 0
  private moduleName: string = ''
  private localCallData: any = {}
  private childData: any = {}
  private customerList: any = []
  private currentCustom: any = {}
  private currentCallData: any = {}
  private currentWebchatData: any = {}
  private webchatLabelArr: any = []
  private webchatProcessData: any = {}
  private moduleLoaded: string = ''
  private appType: string = ''
  private $bus: any
  private $route: any
  private $getCache: any
  private $store: any
  private $message: any
  private webchatLabelTree: any = []
  // 注意：如果默认展示tab-customer组件，会造成qiankun挂载报错（找不到dom）
  // 报错信息：Error: [qiankun] Target container with #apassMicroCustomerData_${moduleType} not existed while apass-micro-customerData loading!
  private activeName: string = ''

  private drawer = {
    title: '定位客户',
    isShow: false
  }

  private tabsList: any = []

  private dockUrlList: any = []

  private realTabsList: any = []

  private lastActiveName = ''

  private showAllNewCuntomer: boolean = false

  private form: any = {
    name: 'name',
    value: ''
  }

  private newCuntomerOptions: any = [
    {
      label: '客户名称',
      prop: 'name'
    },
    {
      label: '手机号',
      prop: 'mobile'
    },
    {
      label: '微信号',
      prop: 'wechat'
    },
    {
      label: '邮箱',
      prop: 'email'
    }
  ]

  private tableData: any = []

  private showTableData: any = []

  private relationCus: any = ''

  private relationCusInfo: any = ''

  private newCusDetailData: any = {} // 客户详情

  private isRelationType: any = ''

  private workShow: boolean = false

  private busCategory: any = []

  private title: any = ''

  private defaultContactor: any = '' // 默认联系人

  private defaultAddr: any = '' // 默认地址

  private initShow: any = true

  get agentListArr () {
    const agents = deepClone(CommonModule.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ key: agents[i]._id, label: agents[i].name })
    }
    return agentsArr
  }

  // 获取当前质检记录状态
  get getQtestingStatus () {
    let qtStatus: string
    if (this.propData.webchatDetails.qualityTime) {
      qtStatus = 'scored'
    } else {
      if (this.propData.webchatDetails.applyQualityTime) {
        qtStatus = 'submitted'
      } else {
        qtStatus = 'notsubmitted'
      }
    }
    return qtStatus
  }

  private getQtText () {
    const qtStatus = this.getQtestingStatus
    if (qtStatus === 'scored') {
      return '已评分'
    } else if (qtStatus === 'submitted') {
      return '撤销质检'
    } else {
      return '提交质检'
    }
  }

  private getQtIcon () {
    const qtStatus = this.getQtestingStatus
    if (qtStatus === 'scored') {
      return 'V7_iconV7tubiao_yitijiaozhijianbingpingfen'
    } else if (qtStatus === 'submitted') {
      return 'V7_iconV7tubiao_yitijiaozhijianweipingfen'
    } else {
      return 'V7_iconV7tubiao_weitijiaozhijian'
    }
  }

  private handleQualitytesting () {
    const currentId: string = this.propData.webchatDetails._id
    const submitStatus = this.getQtestingStatus
    if (submitStatus === 'submitted') {
      this.cancelQualitytesting([currentId])
    } else if (submitStatus === 'notsubmitted') {
      if (this.propData.webchatDetails.status !== 'finish') {
        this.$message.error('当前会话还未结束，无法提交！')
        return false
      }
      if (this.propData.webchatDetails.agentReplyMessageCount === 0) {
        this.$message.error('座席消息数为0，无法提交！')
        return false
      }
      if (this.propData.webchatDetails.userId !== (this.$store.state.common.session.user as any)._id) {
        this.$message.error('座席只能处理本人已结束会话')
        return false
      }
      this.submitQualitytesting([currentId])
    } else {
      console.log('已评分')
      return false
    }
  }

  private updateSqStatus (status) {
    if (status === 'submitted') {
      this.$set(this.propData.webchatDetails, 'applyQualityTime', true)
    } else if (status === 'notsubmitted') {
      this.$set(this.propData.webchatDetails, 'applyQualityTime', false)
    }
  }

  private submitQualitytesting (ids) {
    this.$confirm('提交后您的会话将纳入绩效考核，请确认是否提交！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const url = '/im-center/action/quality/applyQuality'
      const sendData = { _ids: ids }
      const actionData = { url, method: 'POST', data: sendData }
      WebchatModule.webchatCommonAction(actionData).then((res: any) => {
        if (res.success) {
          this.$message.success('会话提交成功')
          this.updateSqStatus('submitted')
        }
      })
    }).catch(() => {
      this.$message.warning('会话提交已取消')
    })
  }

  private cancelQualitytesting (ids) {
    this.$confirm('撤回后，该会话将不会纳入绩效考核，请确认是否撤回！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const url = '/im-center/action/quality/undoApplyQuality'
      const sendData = { _ids: ids }
      const actionData = { url, method: 'POST', data: sendData }
      WebchatModule.webchatCommonAction(actionData).then((res: any) => {
        if (res.success) {
          this.updateSqStatus('notsubmitted')
          this.$message.success('会话撤回成功')
        }
      })
    }).catch(() => {
      this.$message.warning('会话撤回已取消')
    })
  }

  private getCategory () {
    commonAction({
      url: '/server-work/action/workOrderModel/getCategory/filter',
      method: 'post',
      data: { filterPermission: 1 }
    }).then(res => {
      if (res.success) {
        this.busCategory = res.data || []
      }
    })
  }

  private back () {
    this.workShow = false
  }

  private async getDefaultContactor () { // 获取默认联系人
    const params = {
      url: '/server-crm/action/contactor/listAll',
      method: 'POST',
      data: { customerId: this.currentCustom.id }
    }
    const res = await commonAction(params)
    if (res.success && res.data) {
      res.data.list.map(item => {
        if (item.isDefault) {
          this.defaultContactor = item._id
        }
      })
    }
  }

  private async getDefaultAddr () { // 获取默认联系地址
    const params = {
      url: '/server-crm/action/address/listAll',
      method: 'POST',
      data: { customerId: this.currentCustom.id }
    }
    const res = await commonAction(params)
    if (res.success && res.data) {
      res.data.list.map(item => {
        if (item.isDefault) {
          this.defaultAddr = item._id
        }
      })
    }
  }

  private async handleWork (id: any) {
    if (id === 'none') {
      return
    }
    this.workShow = true
    let name = ''
    this.busCategory.forEach(item => {
      if (id === item.id) {
        name = item.modelName
      }
    })
    this.title = `创建的${name}`
    await this.getDefaultContactor()
    await this.getDefaultAddr()
    console.log(this.currentCustom.id, '客户id')
    console.log(this.currentCustom.id, this.defaultContactor, this.defaultAddr, '工单对接参数-在线、通话')
    this.$nextTick(() => {
      this.addOrEditBusinessRef.getBusinessDataById(
        {
          modelId: id,
          info: {
            associateUser: {
              customId: this.currentCustom.id,
              customConcactId: this.defaultContactor,
              customAddressId: this.defaultAddr
            }
          }
        }
      )
    })
  }

  private getMulCon (arr: any, type?: string) {
    let valArr = []
    if (arr && arr.length) {
      valArr = arr.map(item => {
        if (type === 'mobile') {
          return checkHideTel(item.value)
        } else {
          return item.value
        }
      })

      return valArr.join('、')
    }
    return ''
  }

  private getNewCustomerData (searchForm?: any) {
    const params = {
      url: '/server-crm/action/customer/listAll',
      method: 'POST',
      data: searchForm
    }
    commonAction(params).then(res => {
      if (res && res.success && res.data) {
        const resList = res.data.list || []
        resList.map(item => {
          item.mobile = this.getMulCon(item.mobile || [], 'mobile')
          item.email = this.getMulCon(item.email || [])
          item.wechat = this.getMulCon(item.wechat || [])
        })
        this.tableData = resList
        this.showTableData = this.tableData
      }
    })
  }

  private handleSearchNewCus () {
    if (!this.form.name) {
      return this.$message.error('请先选择要搜索的名称')
    }
    if (!this.form.value) {
      this.showTableData = this.tableData
      return
    }
    this.showTableData = this.tableData.filter(item => {
      return (item[this.form.name] && item[this.form.name].indexOf(this.form.value) > -1)
    })
  }

  private chooseCustomer (cus: any) {
    this.relationCusInfo = cus
  }

  private async saveRelationCus () {
    if (!this.relationCusInfo._id) {
      return this.$message.error('请选择客户')
    }
    this.showAllNewCuntomer = false
    this.relationCus = '' // 清空关联数据
    await this.afterAddCustRecord({
      id: this.relationCusInfo._id,
      name: this.relationCusInfo.name,
      labels: this.relationCusInfo.labels
    }) // 更新数据
    this.getNewCusDetail() // 获取客户详情
    if (this.isRelationType === 'create') {
      this.addCusLog('visitor_assign_customer', this.relationCusInfo._id, 'creagte', '', this.visitorId) // 操作日志-关联客户
    } else {
      this.addCusLog('visitor_assign_customer', this.relationCusInfo._id, 'update', '', this.visitorId) // 操作日志-重新关联
    }
  }

  private addCusLog (operateType, customerId, operationType, oldValue, newValue) {
    const params = {
      url: '/server-crm/action/customerLog/add',
      method: 'POST',
      data: {
        operateType,
        customerId,
        changes: [
          {
            fieldKey: 'visitorId',
            operationType,
            oldValue,
            newValue
          }
        ]
      }
    }
    commonAction(params)
  }

  private cancelNewCusListPop () {
    this.form.name = 'name'
    this.showAllNewCuntomer = false
  }

  private relatedCustomers (type) { // create: 关联客户 update: 重新关联
    this.form.value = ''
    this.isRelationType = type
    this.showAllNewCuntomer = true
    this.getNewCustomerData()
  }

  private updateChatCard () {
    this.getSessionInfo(
      this.propData.webchatDetails.visitorId,
      this.propData.webchatDetails._id
    )
  }

  private getSessionInfo (visitorId, id) {
    const params = {
      url: '/im-center/action/webchat/queryChatInfoById',
      method: 'POST',
      data: { visitorId, _id: id }
    }
    WebchatModule.queryChatInfoById(params).then(res => {
      if (res.success) {
        const data: any = {
          custId: '',
          custName: res.chatSession.visitorName,
          type: 'webchat_todo',
          importType: 'webchatTodo',
          webchatDetails: {
            ...this.propData.webchatDetails
          },
          labels: this.currentCustom.labels
        }
        WebchatModule.UPDATE_CUSTOMER_INFO(data)
      }
    })
  }

  private cancelRelationCus () {
    this.$confirm('确认取消关联吗', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const params = {
        url: '/im-center/action/customerNew/deleteCustomerImRelation',
        method: 'POST',
        data: {
          visitorId: this.visitorId
        }
      }
      commonAction(params).then(res => {
        if (res.success) {
          this.addCusLog('cancel_assign_visitor_customer', this.currentCustom.id, 'update', this.visitorId, '') // 操作日志-取消关联
          this.$message.success('取消关联成功')
          this.currentCustom = {
            id: '',
            name: ''
          }
          this.getSessionInfo(
            this.propData.webchatDetails.visitorId,
            this.propData.webchatDetails._id
          )
          this.$nextTick(() => {
            if ((this as any).$refs['tab-customer-new']) {
              (this as any).$refs['tab-customer-new'].init()
            }
          })
        }
      })
    })
  }

  private async getNewCusDetail () {
    const params = { url: `/server-crm/action/customer/${this.currentCustom.id}`, method: 'GET' }
    const res = await commonAction(params)
    if (res.success) {
      this.$set(this, 'newCusDetailData', res.data || {})
      this.$nextTick(() => {
        if ((this as any).$refs['tab-customer-new']) {
          (this as any).$refs['tab-customer-new'].init()
        }
      })
    }
  }

  @Watch('activeName')
  private async activeNameChange (val) {
    if (['tab-record', 'tab-person', 'tab-address'].includes(val)) {
      this.updatePersonOrAddrOrLog(val)
    } else if (['tab-customer-new'].includes(val) && this.initShow) {
      this.initShow = false // 首次进入的时候执行
      if (this.currentCustom.id) {
        await this.getNewCusDetail()
      } else {
        this.$nextTick(() => { // 初始化新客户
          if ((this as any).$refs['tab-customer-new']) {
            (this as any).$refs['tab-customer-new'].init()
          }
        })
      }
    }
  }

  private updatePersonOrAddrOrLog (name) {
    this.$nextTick(() => {
      if (name === 'tab-record' && (this.$refs as any)['tab-record']) {
        (this.$refs as any)['tab-record'].init()
      } else if (name === 'tab-person' && (this as any).$refs['tab-person']) {
        (this as any).$refs['tab-person'].init()
      } else if (name === 'tab-address' && (this as any).$refs['tab-address']) {
        (this as any).$refs['tab-address'].init()
      }
    })
  }

  private get isEmpty () {
    return this.$route.name === 'callCard' && this.$route.params && this.$route.params.id === 'empty'
  }

  get webchatLabelTreeObj () {
    if (this.$store.state.common.publicCache.sessionTagsTreeObj) {
      return this.$store.state.common.publicCache.sessionTagsTreeObj
    } else {
      return []
    }
  }

  @Watch('currentCustom', { immediate: true })
  private watchCurrentCustom (cc) {
    // 排除第一次进入通话模块，点击“外呼”tab时触发；不能去掉immediate，可能会导致刷新系统不触发更新
    if (JSON.stringify(cc) !== '{}') {
      this.componentLoading = true
      this.localCallData.custId = cc.id
      this.localCallData.custName = cc.name
      setTimeout(() => {
        this.componentLoading = false
      }, 500)
      // 为什么不在currentCustom的Watch中触发updateChildrenProps
      // 是因为如果是修改绑定关系后，需要确定请求成功才能触发子组件更新
      // this.updateChildrenProps()
      // if (cc !== 'new' && Object.keys(cc).length > 0) {
      // }
    }
  }

  @Watch('isShowDrawer')
  private drawerChange (val: boolean) {
    if (val === false) {
      this.$nextTick(() => {
        if (this.webchatAddLabelRef) {
          this.webchatAddLabelRef.addLabelHide()
        }
      })
    }
  }

  @Watch('randomNum', { deep: true, immediate: true })
  private randomNumChange (pcd, old) {
    this.updatePropData()
    this.$nextTick(() => {
      this.dockUrlList = []
      if (this.webchatAddLabelRef) {
        this.webchatAddLabelRef.addLabelHide()
        this.webchatAddLabelRef.afoldHide()
      }
    })
  }

  private afoldFun (obj: any) {
    this.labelHeight = obj.isAfold ? obj.height : 0
  }

  public updatePropData () {
    if (Object.keys(this.propData).length > 0) {
      this.componentLoading = true // 如果有问题，可能就是没触发currentCustom的更新
      this.initConfigByImportType(this.propData)
      this.localCallData = JSON.parse(JSON.stringify(this.propData))
      if (!['webchatTodo', 'webchatDataCenter'].includes(this.localCallData.importType)) {
        this.currentCallData = this.localCallData.cdr
        this.customerList = this.localCallData.customerList
      } else {
        const webchatDetails = this.localCallData.webchatDetails
        const { appId, openId } = this.localCallData.visitorInfo || {}
        const unionid = (this.localCallData.visitorInfo && this.localCallData.visitorInfo.weixinVisitorInfo && this.localCallData.visitorInfo.weixinVisitorInfo.unionid) || ''
        const visitorInfo = { appId, openId, unionid }
        this.currentWebchatData = Object.assign(webchatDetails, visitorInfo)
        this.webchatProcessData = this.localCallData.processInfo
        const sessionTags = this.localCallData.webchatDetails.sessionTags || []
        const sessionTagsInfo = this.localCallData.webchatDetails.sessionTagsInfo || []
        const sessionTagsInfoObj = {}
        sessionTagsInfo.forEach(item => {
          sessionTagsInfoObj[item._id] = item
        })
        this.webchatLabelArr = []
        sessionTags.forEach(item => {
          if (this.webchatLabelTreeObj[item]) {
            this.webchatLabelArr.push(this.webchatLabelTreeObj[item])
          } else {
            this.webchatLabelArr.push(sessionTagsInfoObj[item])
          }
        })
        if (Object.keys(this.localCallData.customerList).length > 0) {
          this.customerList = [this.localCallData.customerList]
        } else {
          this.customerList = []
        }
      }
      this.initCatchName()
      this.handleFetchCustomer()
      this.updateChildrenProps()
    }
  }

  private checkHeadersChange (list: any, isInit: boolean) { // tab自定义设置
    if (isInit) {
      return
    }
    const updateList = this.RecoveryLost(this.moduleName, list)
    let actionList = list
    if (updateList && updateList.length > 0) {
      actionList = updateList
      CommonModule.setTabBisacByType({ type: this.moduleName, data: updateList })
    }
    const actionData = { url: '/base/action/general/tab/update', method: 'POST', data: { module: this.moduleName, tabs: actionList } }
    commonAction(actionData)
    this.tabsList = list
    CommonModule.SETTABLIST({ tabList: actionList, module: this.moduleName })
    const index = list.findIndex((item: any) => {
      return item.show
    })
    this.activeName = list[index].pageId
    if (this.propData.importType === 'webchatDataCenter' && this.activeName === 'tab-webchatInfo') {
      this.moduleLoaded = 'tab-WebchatSessionDetails'
    } else {
      this.moduleLoaded = list[index].isSystem ? list[index].pageId : ''
    }
  }

  private RecoveryLost (moduleName: string, updateList: any) {
    // 补全模块丢失的tab 暂时单个处理
    const returnList = deepClone(updateList)
    let flag = false
    let currentId
    let currentTabObj
    if (moduleName === 'call') {
      currentId = 'tab-calldetail'
      currentTabObj = {
        isSystem: true,
        label: '通话详情',
        pageId: 'tab-calldetail',
        show: false
      }
    } else if (moduleName === 'chat') {
      currentId = 'tab-quickReply'
      currentTabObj = {
        isSystem: true,
        label: '常用语',
        pageId: 'tab-quickReply',
        show: false
      }
    } else {
      return false
    }
    updateList.some((item) => {
      if (item.pageId === currentId) {
        flag = true
        return true
      }
    })
    if (!flag) {
      const basicData: any = CommonModule.tabBasicData[moduleName]
      if (basicData && basicData.length > 0) {
        let basicFlag = false;
        let basicIndex = 0;
        let basicObj = {};
        basicData.some((item, index) => {
          if (item.pageId === currentId) {
            basicFlag = true;
            basicIndex = index;
            basicObj = item
            return true
          }
        })
        if (basicFlag) {
          returnList.splice(basicIndex, 0, basicObj)
        } else {
          // 代表已经丢失
          returnList.push(currentTabObj)
        }
      }
    }
    return returnList
  }

  private LocaCustomer (type: string) {
    this.drawer.title = type === 'update' ? '更新客户' : '定位客户'
    this.drawer.isShow = true
  }

  private closeDraw () {
    this.drawer.isShow = false
  }

  private initCatchName () {
    const getVoiceList = this.$getCache('/call/action/general/query', ['ivrList'], false)
    const basicsCatchrequest = Vue.prototype.$getCache('/base/action/general/cache/query', ['queueList', 'userList'], true)
    this.$getCache('/im-center/action/webchat/channelCache', ['channelList'], true)
    Promise.all([getVoiceList, basicsCatchrequest]).then(([voiceLibraryRes, queueListRes]) => {
      voiceLibraryRes.ivrList.some((item) => {
        if (item.nodeId === this.currentCallData.ivrId) {
          this.currentCallData.ivrName = item.name
          return true
        }
      })
      queueListRes.queueList.some((item) => {
        if (item._id === this.currentCallData.queueNumber) {
          this.$set(this.currentCallData, 'queueName', item.name)
          return true
        }
        if (item._id === this.currentWebchatData.toPeer) {
          this.$set(this.currentWebchatData, 'queueName', item.name)
          return true
        }
      })
      if (['webchatTodo', 'webchatDataCenter'].includes(this.localCallData.importType)) {
        if (this.currentWebchatData.agentClaimTimestamp) {
          this.$set(this.currentWebchatData, 'agentClaimTime', formatStamp(this.currentWebchatData.agentClaimTimestamp || 0))
        } else {
          this.$set(this.currentWebchatData, 'agentClaimTime', '')
        }
        if (this.currentWebchatData.firstReplyTimestamp) {
          this.$set(this.currentWebchatData, 'firstReplyTime', formatStamp(this.currentWebchatData.firstReplyTimestamp))
        } else {
          this.$set(this.currentWebchatData, 'firstReplyTime', '')
        }
        const agentObj = this.$store.state.common.publicCache.userListObj[this.currentWebchatData.userId]
        this.$set(this.currentWebchatData, 'userName', (agentObj && agentObj.agentName) || '')
      }
    })
  }

  private initConfigByImportType (config: any) {
    this.activeName = ''
    this.moduleLoaded = ''
    this.appType = ''
    const url = '/base/action/general/tab/list'
    if (['CallCard', 'AutoCallTask', 'DataCenterCall', 'AutoCallTaskScreen'].includes(config.importType)) { // 通话
      this.$nextTick(() => {
        this.moduleName = 'call'
        this.appType = config.cdr.callType || ''
      })
    } else if (['webchatTodo', 'webchatDataCenter'].includes(config.importType)) { // 在线
      this.$nextTick(() => {
        this.moduleName = 'chat'
        this.appType = 'chat'
      })
    }
    this.$nextTick(() => {
      console.log('获取tab数据', this.$store.state.common.tabList)
      if (this.$store.state.common.tabList[this.moduleName]) {
        this.tabsList = deepClone(this.$store.state.common.tabList[this.moduleName])
        this.tabListhandle(config)
      } else {
        const actionData = { url, method: 'POST', data: { module: this.moduleName, scene: this.appType } }
        commonAction(actionData).then(res => {
          if (res && res.success && res.data.length > 0) {
            CommonModule.setTabBisacByType({ type: this.moduleName, data: deepClone(res.data) })
            CommonModule.SETTABLIST({ tabList: deepClone(res.data), module: this.appType })
            this.tabsList = deepClone(res.data)
            this.realTabsList = deepClone(res.data)
            this.tabListhandle(config)
          }
        })
      }
    })
  }

  private tabListhandle (config) {
    if (['DataCenterCall', 'AutoCallTask'].indexOf(config.importType) > -1) {
      if (this.tabsList.find((v: any) => v.pageId === 'tab-calldetail') === undefined) {
        this.tabsList.unshift({ label: '通话详情', pageId: 'tab-calldetail', show: true, isSystem: true, disabled: true })
      }
    } else if (['CallCard', 'AutoCallTaskScreen'].indexOf(config.importType) > -1) {
      const index = this.tabsList.findIndex(item => {
        return item.pageId === 'tab-calldetail'
      })
      if (index > -1) {
        this.tabsList.splice(index, 1)
      }
    } else if (config.importType === 'webchatDataCenter') {
      const index = this.tabsList.findIndex(item => {
        return item.pageId === 'tab-quickReply'
      })
      if (index > -1) {
        this.tabsList.splice(index, 1)
      }
    } else if (config.importType === 'webchatTodo') {
      this.tabsList = deepClone(this.realTabsList).length > 0 ? deepClone(this.realTabsList) : this.tabsList
    }
    const showTabPage = this.tabsList.find(item => {
      return item.show
    })
    this.setFunTabName(showTabPage.pageId)
  }

  private handleFetchCustomer () {
    if (this.customerList.length === 0) {
      this.currentCustom = { id: '', name: '' }
    } else if (['CallCard', 'DataCenterCall', 'AutoCallTask', 'AutoCallTaskScreen'].includes(this.localCallData.importType)) { // 通话
      this.currentCustom = this.customerList.find(v => v.id === this.localCallData.custId) || { id: '', name: '多个客户' }
    } else { // 在线
      this.currentCustom = { name: this.customerList[0].customerName, id: this.customerList[0].customerId }
    }
    if ((this as any).$store.state.common.session.account.mpShifted) { // 新客户初次进入
      this.initShow = true
    }
  }

  private async handleCommand (command) { // 切换小蓝条的客户
    // 重复点击不触发更新
    if (JSON.stringify(this.currentCustom) !== JSON.stringify(command)) {
      this.currentCustom = command
      if (command === 'new') {
        this.updateChildrenProps()
      } else {
        this.changeCustomerRelation('change')
        // 如果是 数据中心-通话记录 的修改，触发更新通话弹屏的组件内容
        if (['DataCenterCall', 'AutoCallTask'].includes(this.localCallData.importType)) {
          this.$bus.$emit('updateCrdLocateCustList', { // 更新全部客户信息
            phone: this.localCallData.phone,
            id: this.currentCustom.id,
            name: this.currentCustom.name
          })
        }
      }

      if ((this as any).$store.state.common.session.account.mpShifted) {
        this.getNewCusDetail() // 更新客户
        this.updatePersonOrAddrOrLog(this.activeName) // 更新tab-联系人、联系地址、修改记录
      }
    }
  }

  private changeCustomerRelation (type: string, addData: any = {}) { // 外抛事件
    const data = {
      ...this.localCallData,
      type,
      timeStamp: new Date().getTime(), // 时间戳
      custId: this.currentCustom.id,
      custName: this.currentCustom.name,
      labels: this.currentCustom.labels
    }
    if (type === 'add' && ['CallCard', 'DataCenterCall', 'AutoCallTask', 'AutoCallTaskScreen'].includes(this.localCallData.importType)) { // 通话
      data.addData = addData // 新增的数据
      if (data.customerList.find(v => v.id === addData.id) === undefined) { // 查缺补漏.gif
        data.customerList.unshift({ // 把最新客户unshift到第一个
          id: addData.id,
          name: addData.name
        })
      }
    }
    const actionData = {
      url: '/call/action/cdrRelation/save',
      method: 'POST',
      data: {}
    }
    if (['webchatTodo', 'webchatDataCenter'].includes(this.localCallData.importType)) { // 在线关联客户请求数据
      const sendWebchatData = { chatSessionId: data.webchatDetails._id, customerId: data.custId, customerName: data.custName }
      if (type === 'add' || this.customerList.length === 0) {
        actionData.url = this.$store.state.common.session.account.mpShifted ? '/im-center/action/customerNew/locationCustomer' : '/im-center/action/customer/locationCustomer'
      } else {
        actionData.url = '/im-center/action/customer/update'
        delete sendWebchatData.chatSessionId
      }
      actionData.data = this.$store.state.common.session.account.mpShifted ? { ...sendWebchatData, visitorId: this.visitorId } : sendWebchatData
    } else {
      const sendCallData = { superUniqueId: data.callSheetId, customerId: data.custId, customerName: data.custName }
      actionData.data = sendCallData
    }
    commonAction(actionData).then(resp => {
      if (resp && resp.success) {
        if (type === 'change') {
          this.updateChildrenProps()
        }
        this.$emit('changeCustomerRelation', data)
      }
    }).catch(err => { console.log(err) })
  }

  // 更新子组件的prop数据，即更新当前客户后触发，
  private updateChildrenProps () {
    this.childData = {
      ...this.localCallData,
      timeStamp: new Date().getTime(), // 时间戳
      custId: this.currentCustom.id,
      custName: this.currentCustom.name
    }
  }

  private afterAddCustRecord (data) {
    this.currentCustom = {
      id: data.id,
      name: data.name,
      labels: data.labels
    }
    this.$bus.$emit('updateCrdLocateCustList', data) // 更新全部客户信息
    this.changeCustomerRelation('add', data)
  }

  private afterEditCustRecord (data) {
    this.currentCustom.name = data.name
    this.$bus.$emit('updateCrdLocateCustList', data) // 更新全部客户信息
    this.changeCustomerRelation('edit', data)
  }

  private async setFunTabName (name: string) {
    if (![ // 自定义tab页
      'tab-customer',
      'tab-customer-new',
      'tab-person',
      'tab-address',
      'tab-record',
      'tab-webchatInfo',
      'tab-ticket',
      'tab-contact',
      'tab-calldetail',
      'tab-quickReply',
      'tab-WebchatSessionDetails'].includes(name)) { // iframe 对接页
      const isHasDockNameList = this.dockUrlList.some(item => {
        return item.name === name
      })
      if (!isHasDockNameList) {
        await this.tabUrl(name)
      } else {
        const currentDock = this.dockUrlList.filter(item => {
          return item.name === name
        })
        this.childData.currentDockPageUrl = currentDock ? currentDock[0] : { name: '', url: '' }
      }
      this.moduleLoaded = ''
    } else { // 系统页
      if (this.propData.importType === 'webchatDataCenter' && name === 'tab-webchatInfo') {
        this.moduleLoaded = 'tab-WebchatSessionDetails'
      } else {
        this.moduleLoaded = name
      }
    }
    this.activeName = name
  }

  private async tabUrl (name: string) {
    const urlIndex = this.tabsList.findIndex((item: any) => {
      return name === item.pageId
    })
    const urlParmers = this.tabsList[urlIndex].parameters // 对接参数
    const isToken = this.tabsList[urlIndex].isToken // 是否开启了token身份验证
    let url = this.tabsList[urlIndex].url
    const cardInfo = this.moduleName === 'chat' ? this.currentWebchatData : this.localCallData.cdr
    if (urlParmers) {
      url = this.dockUrlHandle({ type: this.moduleName, url, urlParmers, cardInfo })
    }
    if (isToken) { // 开启token身份验证
      const actionData = { url: '/auth/token', method: 'GET', data: {} }
      await commonAction(actionData).then(res => {
        if (res && res.success) {
          const tokenId = res.data.token || ''
          url = `${url}&tokenId=${tokenId}`
        }
      })
    }
    this.dockUrlList.push({ url, name })
    this.childData.currentDockPageUrl = { url, name }
  }

  private async newTabClick (name: string) { // 对接页新窗口打开
    await this.tabUrl(name)
    window.open(this.childData.currentDockPageUrl.url)
  }

  private dockUrlHandle (obj: any) {
    if (obj.url.indexOf('?') === -1) {
      obj.url = obj.url + '?'
    } else {
      if (obj.url.substring(obj.url.length - 1) !== '?') {
        obj.url = obj.url + '&'
      }
    }
    if (obj.urlParmers.length > 0) {
      const dk = this.$store.state.common.dk
      obj.urlParmers.forEach((item: any, index: number) => {
        if (item.originParam === 'account') {
          item.originParam = obj.type === 'call' ? 'accountId' : 'account'
        }
        if (item.originParam === 'queueNumber') {
          item.originParam = obj.type === 'call' ? 'queueNumber' : 'toPeer'
        }
        if (item.originParam === 'customerName') { // 因客户名称存储方式不同，需特殊处理
          const customName = encodeURI(deepClone(this.currentCustom.name))
          obj.url += this.handleTabUrl({
            index,
            dk,
            customParam: item.customParam,
            originParam: item.originParam,
            cardInfo: customName || '',
            encrypted: item.encrypted
          })
        } else {
          if (item.originParam === 'visitorName') {
            const visitorName = encodeURI(deepClone(obj.cardInfo[item.originParam]))
            obj.url += this.handleTabUrl({
              index,
              dk,
              customParam: item.customParam,
              originParam: item.originParam,
              cardInfo: visitorName || '',
              encrypted: item.encrypted
            })
          } else if (item.originParam === 'customerNumber') {
            const customerNumber = obj.cardInfo[item.originParam] || obj.cardInfo.number
            obj.url += this.handleTabUrl({
              index,
              dk,
              customParam: item.customParam,
              originParam: item.originParam,
              cardInfo: customerNumber || '',
              encrypted: item.encrypted
            })
          } else {
            obj.url += this.handleTabUrl({
              index,
              customParam: item.customParam,
              originParam: item.originParam,
              dk,
              cardInfo: obj.cardInfo[item.originParam] || '',
              encrypted: item.encrypted
            })
          }
        }
      })
    }
    if (obj.type === 'chat' && obj.cardInfo.userParams) { // 在线自定义参数
      const userParams = deepClone(JSON.stringify(obj.cardInfo.userParams))
      obj.url = obj.url + `&userParams=${encodeURI(userParams)}`
    }
    obj.url = obj.url + `&tabType=${obj.type}`
    return obj.url
  }

  private handleTabUrl ({ index, customParam, originParam, dk, cardInfo, encrypted }) {
    // 有自定义名称参数用自定义的否则用原生的，开启了加密要进行aes加密
    return `${index === 0 ? '' : '&'}${customParam || originParam}=${cardInfo
      ? encrypted ? encrypt(cardInfo, dk) : cardInfo : ''}`
  }

  private handleOprate (list: any) {
    this.$set(this, 'handleOprateArr', list)
  }

  private webchatAddLabel (data: any) {
    let sessionTagsInfo: any = []
    for (let i = 0; i < data.length; i++) {
      sessionTagsInfo.push(this.webchatLabelTreeObj[data[i][data[i].length - 1]])
    }
    sessionTagsInfo = [...this.webchatLabelArr, ...sessionTagsInfo]
    if (sessionTagsInfo.length > 10) {
      this.$message.error('最多只能打10个标签')
      return
    }
    const newSessionTagsInfo = sessionTagsInfo.map(item => item._id)
    const arrSet = new Set(newSessionTagsInfo)
    if (arrSet.size !== newSessionTagsInfo.length) {
      this.$message.error('当前有重复标签')
      return
    }
    const { sessionId } = this.localCallData.webchatDetails
    const actionData = {
      url: '/im-center/action/webchat/addSessionTag',
      method: 'POST',
      data: {
        sessionId: sessionId || this.localCallData.webchatDetails._id, sessionTagsInfo
      }
    }
    commonAction(actionData).then(res => {
      if (res && res.success) {
        this.$message.success('添加标签成功')
        this.webchatLabelArr = sessionTagsInfo
        this.$nextTick(() => {
          if (this.webchatAddLabelRef) {
            this.webchatAddLabelRef.addSuccessFun()
          }
        })
      }
    })
  }

  private mounted () {
    this.webchatLabelTree = []
    if (this.$store.state.common.publicCache.sessionTags) {
      const sessionTagsTree = this.$store.state.common.publicCache.sessionTags.tree
      handTagTree(sessionTagsTree, { Arr: this.webchatLabelTree })
    }
    this.$getCache('/crm/action/ticket/cache', ['ticketList'], false).then((data: any) => {
      // console.log('mopower cache data ticketList:\n', data.ticketList)
    })
    this.$getCache('/crm/action/customer/config/cache', ['customerList'], false).then((data: any) => {
      // console.log('mopower cache data customerList:\n', data.customerList)
    })
    this.$bus.$on('updateCrdLocateCustList', (saveData: any) => {
      // 仅更新通话卡片处
      if (['CallCard', 'AutoCallTask', 'AutoCallTaskScreen'].includes(this.localCallData.importType)) {
        // 展示的是同一个手机号的，都修改customerList
        if (saveData.phone === this.localCallData.phone) {
          // 1. 修改customerList
          if (this.customerList.find(v => v.id === saveData.id)) {
            // 如果已存在当前客户，即修改操作
            this.customerList.find(v => v.id === saveData.id).name = saveData.name
          } else {
            // 如果不存在，即新增操作，unshift到第一个
            this.customerList.unshift({
              id: saveData.id,
              name: saveData.name
            })
          }
          this.localCallData.customerList = this.customerList
          // 如果展示的是当前callSheetId
          // 2. 修改currentCustom
          if (this.currentCustom.id === '') { // && this.currentCustom.name === '多个客户'
            // 2.1 如果当前未绑定客户
            this.currentCustom.id = saveData.id
            this.currentCustom.name = saveData.name
            this.updateChildrenProps()
          } else if (this.currentCustom.id === saveData.id) {
            // 2.2 如果当前展示的是同一客户，即修改操作触发
            this.currentCustom.name = saveData.name
            this.updateChildrenProps()
          }
        }
      } else if (['DataCenterCall', 'AutoCallTask'].includes(this.localCallData.importType)) {
        // 同步传给子组件的prop
        this.updateChildrenProps()
      } else if (['webchatDataCenter', 'webchatTodo'].includes(this.localCallData.importType)) {
        this.localCallData.customerList = this.customerList
        // 2. 修改currentCustom
        if (this.currentCustom.id === '') {
          // 2.1 如果当前未绑定客户
          this.currentCustom.id = saveData.id
          this.currentCustom.name = saveData.name
          this.updateChildrenProps()
        } else if (this.currentCustom.id === saveData.id) {
          // 2.2 如果当前展示的是同一客户即修改操作触发
          this.currentCustom.name = saveData.name
          this.updateChildrenProps()
        }
      }
    })

    if (this.$store.state.common.session.account.mpShifted) { // 新客户接口
      this.getCategory() // 获取工单
      this.$getCache('/server-crm/action/customer/common/panel/insert', ['customerInputConfig'], false, false, false, 'GET', false, 'data.fields') // 录入面板配置
      this.$getCache('/server-crm/action/customer/common/labels', ['customerAllLabels'], true, false, false, 'GET', false, 'data') // 客户标签
      this.$getCache('/base/action/general/cache/query', ['region'], false) // 省市区
    }
  }
}
</script>

<style lang="stylus" scoped>
.current-name
  flex 1
  overflow hidden
  word-break keep-all
  white-space nowrap
  text-overflow ellipsis
.work
  >>> .el-dialog__header
    padding 0
    margin-bottom 0
  >>> .el-dialog__body
    padding 0
.new-customer
  .btns
    width 100%
    text-align right
    margin-top 20px
    .el-button
      width 60px
      height 32px
  >>> .el-input__prefix
    line-height 32px
.call-right-box
  width 100%
  background #fff
  overflow auto
.shadow
  box-shadow 0px 0px 4px 0px #E0E6F0, 0px 1px 4px 0px #E0E6F0
.isCallCard
  border-radius 10px
  padding 16px
  height 100%
  // overflow-y scroll
.isDataCenterCall, .empty
  overflow hidden
.empty:before
  content ''
  display block
  position absolute
  width 100%
  height 100%
  background white url('../../assets/img/no-data.png') no-repeat center center
  background-size 267px auto
  border-radius 10px
  z-index 20
  top 0
  bottom 0
.callSummary
  position relative
  display block
// 客户卡片小蓝条
.call-customer-card
  height 68px
  background-color #E5F3FD
  border-radius 4px
  // margin-bottom 8px
  .item-left
    height inherit
    line-height 68px
    display flex
    align-items center
    justify-content center
    padding 0 0 0 24px
    .agent-img
      width 40px
      height 40px
      border-radius 50%
  .item-right
    width 100%
    height 100%
    padding 0px 20px
    .first-line
      margin-top 12px
      height 16px
      line-height 16px
      .customer-name
        color $fc-gray2
        font-size 12px
        font-weight bold
        cursor pointer
      & >>> .el-button--text
        padding 0
        span
          padding-left 0
    .second-line
      margin-top 12px
      height 16px
      line-height 16px
      .customer-info
        color $fc-gray3
      .customer-info + .customer-info
        margin-left 20px
      .processInfo:hover
        color #1890ff
      .peer
        max-width 160px
        overflow hidden
        display inline-block
        word-break break-all
        text-overflow ellipsis
        white-space nowrap
        vertical-align middle
.el-dropdown-menu
  padding-top 1px
  padding-bottom 1px
  max-height 300px
  width auto
  overflow auto
.processInfo
  cursor pointer
  margin 0px 20px
.positioning
  color #008BEE
  cursor pointer
.V7_iconfont
  font-size 12px
.webchatAddLabel
  width 100%
  border 1px solid $border-main
  border-radius 0px 0px 4px 4px
  border-top none
  padding 6px 0px
  margin-bottom 8px
</style>
